import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from '@/config/database';

// 定义岗位属性接口
interface PostAttributes {
  postId: number;
  postCode: string;
  postName: string;
  postSort: number;
  status: string;
  createBy?: string;
  createTime?: Date;
  updateBy?: string;
  updateTime?: Date;
  remark?: string;
  flag?: boolean; // 用户是否存在此岗位标识，前端用
}

// 创建时可选的字段
interface PostCreationAttributes extends Optional<PostAttributes, 'postId'> {}

// 岗位模型类
class Post extends Model<PostAttributes, PostCreationAttributes> implements PostAttributes {
  public postId!: number;
  public postCode!: string;
  public postName!: string;
  public postSort!: number;
  public status!: string;
  public createBy?: string;
  public createTime?: Date;
  public updateBy?: string;
  public updateTime?: Date;
  public remark?: string;
  public flag?: boolean;

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 检查岗位状态是否正常
  public isActive(): boolean {
    return this.status === '0';
  }
}

Post.init(
	{
		postId: {
			type: DataTypes.BIGINT,
			primaryKey: true,
			autoIncrement: true,
			field: "post_id",
			get() {
				// 确保返回数字类型
				const value = this.getDataValue('postId');
				return value !== undefined ? Number(value) : undefined;
			}
		},
		postCode: {
			type: DataTypes.STRING(64),
			allowNull: false,
			field: "post_code",
		},
		postName: {
			type: DataTypes.STRING(50),
			allowNull: false,
			field: "post_name",
		},
		postSort: {
			type: DataTypes.INTEGER,
			allowNull: false,
			field: "post_sort",
			get() {
				// 确保返回数字类型
				const value = this.getDataValue('postSort');
				return value !== undefined ? Number(value) : undefined;
			}
		},
		status: {
			type: DataTypes.CHAR(1),
			allowNull: false,
			defaultValue: "0", // 0正常 1停用
			field: "status",
		},
		createBy: {
			type: DataTypes.STRING(64),
			field: "create_by",
		},
		createTime: {
			type: DataTypes.DATE,
			field: "create_time",
		},
		updateBy: {
			type: DataTypes.STRING(64),
			field: "update_by",
		},
		updateTime: {
			type: DataTypes.DATE,
			field: "update_time",
		},
		remark: {
			type: DataTypes.STRING(500),
			defaultValue: "", // 设置默认值为空字符串
			field: "remark",
		},
	},
	{
		sequelize,
		tableName: "sys_post",
		timestamps: true,
		createdAt: "createTime",
		updatedAt: "updateTime",
	}
);

export default Post; 